-- Lua Battle System - 角色基类

local Logger = require("utils.logger")
local TableUtils = require("utils.table_utils")
local StatusEffects = require("characters.status_effects")

local Character = {
    -- 角色属性
    id = "",
    name = "",
    level = 1,
    
    -- 基础属性
    max_hp = 100,
    hp = 100,
    max_mp = 50,
    mp = 50,
    attack = 20,
    defense = 10,
    magic_attack = 15,
    magic_defense = 8,
    speed = 15,
    luck = 10,
    
    -- 战斗相关属性
    team_id = 1,
    position = 1,
    is_alive = true,
    is_controlled = false, -- 是否被玩家控制
    
    -- 状态效果
    status_effects = {},
    
    -- 技能和物品
    skills = {},
    items = {},
    
    -- 装备
    equipment = {
        weapon = nil,
        armor = nil,
        accessory = nil
    },
    
    -- AI
    ai = nil
}

-- 角色构造函数
function Character:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    o:init()
    return o
end

-- 初始化角色
function Character:init()
    self.hp = self.max_hp
    self.mp = self.max_mp
    self.is_alive = true
    self.status_effects = {}
    self.skills = {}
    self.items = {}
    self.equipment = {
        weapon = nil,
        armor = nil,
        accessory = nil
    }
    
    Logger.debug("角色初始化完成: " .. self.name)
end

-- 获取角色当前属性
function Character:get_current_stats()
    local stats = {
        hp = self.hp,
        mp = self.mp,
        attack = self.attack,
        defense = self.defense,
        magic_attack = self.magic_attack,
        magic_defense = self.magic_defense,
        speed = self.speed,
        luck = self.luck
    }
    
    -- 应用状态效果对属性的影响
    for _, effect in pairs(self.status_effects) do
        if effect.modify_stats then
            stats = effect:modify_stats(stats)
        end
    end
    
    return stats
end

-- 受到伤害
function Character:take_damage(damage)
    local current_stats = self:get_current_stats()
    local final_damage = math.max(1, damage - current_stats.defense * 0.5)
    
    self.hp = self.hp - final_damage
    if self.hp <= 0 then
        self.hp = 0
        self.is_alive = false
        Logger.info(self.name .. " 受到 " .. final_damage .. " 点伤害，已阵亡")
    else
        Logger.info(self.name .. " 受到 " .. final_damage .. " 点伤害，剩余生命值: " .. self.hp)
    end
    
    return final_damage
end

-- 恢复生命值
function Character:heal(amount)
    self.hp = math.min(self.max_hp, self.hp + amount)
    Logger.info(self.name .. " 恢复了 " .. amount .. " 点生命值，当前生命值: " .. self.hp)
    return amount
end

-- 消耗魔法值
function Character:consume_mp(amount)
    if self.mp < amount then
        Logger.warn(self.name .. " 魔法值不足，当前魔法值: " .. self.mp .. "，需要: " .. amount)
        return false
    end
    
    self.mp = self.mp - amount
    Logger.debug(self.name .. " 消耗了 " .. amount .. " 点魔法值，剩余魔法值: " .. self.mp)
    return true
end

-- 恢复魔法值
function Character:recover_mp(amount)
    self.mp = math.min(self.max_mp, self.mp + amount)
    Logger.info(self.name .. " 恢复了 " .. amount .. " 点魔法值，当前魔法值: " .. self.mp)
    return amount
end

-- 添加状态效果
function Character:add_status_effect(effect)
    local existing_effect = self.status_effects[effect.id]
    if existing_effect then
        -- 如果状态效果已存在，尝试堆叠
        if existing_effect:stack(effect) then
            Logger.info(self.name .. " 获得了 " .. effect.name .. " 状态效果，当前层数: " .. existing_effect.stacks)
        end
    else
        -- 添加新状态效果
        self.status_effects[effect.id] = effect
        effect:on_apply(self)
        Logger.info(self.name .. " 获得了 " .. effect.name .. " 状态效果")
    end
end

-- 移除状态效果
function Character:remove_status_effect(effect_id)
    local effect = self.status_effects[effect_id]
    if effect then
        effect:on_remove(self)
        self.status_effects[effect_id] = nil
        Logger.info(self.name .. " 移除了 " .. effect.name .. " 状态效果")
    end
end

-- 清除所有状态效果
function Character:clear_status_effects()
    for effect_id, effect in pairs(self.status_effects) do
        effect:on_remove(self)
    end
    self.status_effects = {}
    Logger.info(self.name .. " 清除了所有状态效果")
end

-- 更新状态效果
function Character:update_status_effects()
    for effect_id, effect in pairs(self.status_effects) do
        effect:update(self)
        if effect.duration <= 0 then
            self:remove_status_effect(effect_id)
        end
    end
end

-- 添加技能
function Character:add_skill(skill)
    table.insert(self.skills, skill)
    Logger.debug(self.name .. " 学会了技能: " .. skill.name)
end

-- 移除技能
function Character:remove_skill(skill_id)
    for i, skill in ipairs(self.skills) do
        if skill.id == skill_id then
            table.remove(self.skills, i)
            Logger.debug(self.name .. " 忘记了技能: " .. skill.name)
            return true
        end
    end
    return false
end

-- 添加物品
function Character:add_item(item, quantity)
    quantity = quantity or 1
    self.items[item.id] = (self.items[item.id] or 0) + quantity
    Logger.debug(self.name .. " 获得了 " .. quantity .. " 个 " .. item.name)
end

-- 使用物品
function Character:use_item(item_id, target)
    local quantity = self.items[item_id]
    if not quantity or quantity <= 0 then
        Logger.warn(self.name .. " 没有足够的 " .. item_id .. " 物品")
        return false
    end
    
    -- 调用物品使用方法
    local success = item:use(self, target)
    if success then
        self.items[item_id] = quantity - 1
        if self.items[item_id] <= 0 then
            self.items[item_id] = nil
        end
        Logger.info(self.name .. " 使用了 " .. item.name)
    end
    
    return success
end

-- 装备物品
function Character:equip_item(item)
    if item.type ~= "equipment" then
        Logger.warn(item.name .. " 不是装备物品")
        return false
    end
    
    local slot = item.equipment_slot
    if not slot then
        Logger.warn(item.name .. " 没有指定装备槽位")
        return false
    end
    
    -- 卸下当前装备
    local current_equipment = self.equipment[slot]
    if current_equipment then
        self:unequip_item(slot)
    end
    
    -- 装备新物品
    self.equipment[slot] = item
    item:on_equip(self)
    Logger.info(self.name .. " 装备了 " .. item.name)
    return true
end

-- 卸下装备
function Character:unequip_item(slot)
    local equipment = self.equipment[slot]
    if not equipment then
        Logger.warn(self.name .. " 没有装备 " .. slot .. " 槽位的物品")
        return false
    end
    
    equipment:on_unequip(self)
    self.equipment[slot] = nil
    Logger.info(self.name .. " 卸下了 " .. equipment.name)
    return true
end

-- 行动顺序计算
function Character:get_action_priority()
    local current_stats = self:get_current_stats()
    return current_stats.speed + math.random(0, 10)
end

-- 执行行动
function Character:execute_action(action, target)
    Logger.info(self.name .. " 执行了行动: " .. action.name)
    return action:execute(self, target)
end

-- 获取角色状态
function Character:get_state()
    return {
        id = self.id,
        name = self.name,
        level = self.level,
        hp = self.hp,
        max_hp = self.max_hp,
        mp = self.mp,
        max_mp = self.max_mp,
        attack = self.attack,
        defense = self.defense,
        magic_attack = self.magic_attack,
        magic_defense = self.magic_defense,
        speed = self.speed,
        luck = self.luck,
        team_id = self.team_id,
        position = self.position,
        is_alive = self.is_alive,
        is_controlled = self.is_controlled,
        status_effects = TableUtils.map(self.status_effects, function(_, effect) return effect:get_state() end),
        skills = TableUtils.map(self.skills, function(_, skill) return skill:get_state() end),
        items = self.items,
        equipment = TableUtils.map(self.equipment, function(_, equip) return equip and equip:get_state() or nil end)
    }
end

-- 序列化角色
function Character:serialize()
    local state = self:get_state()
    return TableUtils.tostring(state)
end

-- 反序列化角色
function Character:deserialize(data)
    local state = TableUtils.fromstring(data)
    if not state then
        Logger.error("角色反序列化失败，无效的数据格式")
        return false
    end
    
    return self:from_state(state)
end

-- 从状态数据恢复角色
function Character:from_state(state)
    -- 基本属性
    self.id = state.id or self.id
    self.name = state.name or self.name
    self.level = state.level or self.level
    
    -- 基础属性
    self.max_hp = state.max_hp or self.max_hp
    self.hp = state.hp or self.hp
    self.max_mp = state.max_mp or self.max_mp
    self.mp = state.mp or self.mp
    self.attack = state.attack or self.attack
    self.defense = state.defense or self.defense
    self.magic_attack = state.magic_attack or self.magic_attack
    self.magic_defense = state.magic_defense or self.magic_defense
    self.speed = state.speed or self.speed
    self.luck = state.luck or self.luck
    
    -- 战斗相关属性
    self.team_id = state.team_id or self.team_id
    self.position = state.position or self.position
    self.is_alive = state.is_alive or self.is_alive
    self.is_controlled = state.is_controlled or self.is_controlled
    
    -- 状态效果（需要特殊处理，因为状态效果是对象）
    if state.status_effects then
        self.status_effects = {}
        for _, effect_state in ipairs(state.status_effects) do
            local effect = StatusEffects.create_effect(effect_state.id, effect_state.params)
            if effect then
                effect:from_state(effect_state)
                self.status_effects[effect.id] = effect
            end
        end
    end
    
    -- 技能和物品（需要特殊处理，因为技能是对象）
    -- 注意：技能和物品的反序列化需要更复杂的逻辑，这里简化处理
    -- 实际应用中，应该从技能管理器和物品管理器中获取完整的技能和物品对象
    self.skills = state.skills or self.skills
    self.items = state.items or self.items
    self.equipment = state.equipment or self.equipment
    
    Logger.info(self.name .. " 角色状态恢复完成")
    return true
end

-- 导出模块
return Character